package dao

import (
	"mldong/internal/modules/sys/entity"
	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
)

type UserRoleDao struct {
}

// r_用户角色关系
// 根据用户ID获取用户角色
func (u *UserRoleDao) GetByUserId(userId string) (res []entity.UserRole, err error) {
	err = g.Model("sys_user_role").Where("user_id=?", userId).Scan(&res)
	return res, err
}

// 根据角色ID获取用户角色
func (u *UserRoleDao) GetByRoleId(roleId string) (res []entity.UserRole, err error) {
	err = g.Model("sys_user_role").Where("role_id=?", roleId).Scan(&res)
	return res, err
}

// 插入用户角色
func (u *UserRoleDao) Insert(entity entity.UserRole, tx gdb.TX) (res entity.UserRole, err error) {
	if entity.ID == nil {
		entity.ID = utility.GenId()
	}
	_, err = u.Model(tx).Data(entity).Insert()
	return entity, err
}

// 判断用户角色是否存在
func (u *UserRoleDao) Exists(userId string, roleId string) (res bool, err error) {
	count, err := g.Model("sys_user_role").Where("user_id=? and role_id=?", userId, roleId).Count()
	if err != nil {
		return false, err
	}
	res = count > 0
	return res, err
}

// 删除用户角色
func (u *UserRoleDao) Remove(userId string, roleId string) (res bool, err error) {
	_, err = g.Model("sys_user_role").Where("user_id=? and role_id=?", userId, roleId).Delete()
	return true, err
}

// 获取sys_user_role模型
func (u *UserRoleDao) Model(tx gdb.TX) *gdb.Model {
	var model *gdb.Model
	if tx != nil {
		model = tx.Model("sys_user_role")
	} else {
		model = g.Model("sys_user_role")
	}
	return model
}
func NewUserRoleDao() *UserRoleDao {
	return &UserRoleDao{}
}
